package nobu.nakata.nfcfare.resource.mapper.strategy;

import java.util.Date;

import javax.jdo.PersistenceManager;

import net.sf.jsr107cache.Cache;
import nobu.nakata.nfcfare.datamapper.BusStationDataMapper;
import nobu.nakata.nfcfare.datamapper.BusStationHistoryDataMapper;
import nobu.nakata.nfcfare.resource.item.IBusResourceItem;
import nobu.nakata.nfcfare.resource.item.impl.BusResourceItem;
import nobu.nakata.nfcfare.resource.mapper.IPersistenceStrategy;
import nobu.nakata.nfcfare.table.BusStation;
import nobu.nakata.nfcfare.table.BusStationHistory;

import com.google.appengine.api.users.User;


public class BusPersistence implements IPersistenceStrategy<IBusResourceItem, Long> {
	private Cache cache;
	private PersistenceManager pm;
	private User viewer;
	
	private BusStationDataMapper _stationList;
	private BusStationHistoryDataMapper _historyList;
	
	public BusPersistence(Cache cache, PersistenceManager pm, User viewer) {
		this.cache		= cache;
		this.pm			= pm;
		this.viewer		= viewer;
	}

	@Override
	public IBusResourceItem get(Long key) {
		BusStation station = getStationListGateway().findByBusCode(key);
		if (station == null)
			return null;
		return new BusResourceItem(key, station.getName());
	}

	@Override
	public void set(IBusResourceItem item) {
		getStationHistoryGateway().set(new BusStationHistory(
				item.getBusCode(), item.getName(), viewer, (new Date()).getTime()));
		getStationListGateway().set(new BusStation(item.getBusCode(), item.getName()));
	}

	@Override
	public void remove(IBusResourceItem item) {
		throw new RuntimeException("Not implemented yet"); 
	}

	private BusStationDataMapper getStationListGateway() {
		if (_stationList == null)
			_stationList = new BusStationDataMapper(cache, pm);
		return _stationList;
	}
	private BusStationHistoryDataMapper getStationHistoryGateway() {
		if (_historyList == null)
			_historyList = new BusStationHistoryDataMapper(cache, pm);
		return _historyList;
	}
}